package top.easycode.app.controller;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import top.easycode.app.common.BaseResult;
import top.easycode.app.util.RequestUtil;

import javax.servlet.http.HttpServletRequest;

@Service
public class APPBusinessServiceImpl implements APPBusinessService,
		ApplicationContextAware, DisposableBean {

	private static final Logger log = LoggerFactory
			.getLogger(APPBusinessServiceImpl.class);

	private ApplicationContext applicationContext;

	@Override
	public BaseResult dispose(HttpServletRequest request, String application,
							  String context, String type) {
		String userId = request.getHeader("userId");
		String ip = RequestUtil.getIpAddr(request);
		// 处理由x-forward-for属性拿到的ip中包含代理服务器ip的情况
		if (ip != null && ip.contains(",")) {
			log.info("该客户端有代理服务器 X-Forward-For 为 " + ip);
			String[] ips = ip.split(",");
			ip = ips[ips.length - 1].trim();
			log.info("处理后的ip为 " + ip);
		}

		IBaseProcess service = (IBaseProcess) applicationContext.getBean(this
				.getServiceNameFromApplication(application));
		return service.process(context, type, userId, ip);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		log.debug("注入ApplicationContext到SpringContextUtils:"
				+ applicationContext);
		this.applicationContext = applicationContext; // NOSONAR
	}

	@Override
	public void destroy() throws Exception {
		log.debug("清除SpringContextUtils中的ApplicationContext:"
				+ applicationContext);
		applicationContext = null;
	}

	/**
	 * <B>方法名称：</B>getServiceNameFromApplication<BR>
	 * <B>概要说明：</B>将context中的application转换成service对应的key<BR>
	 *
	 * @param application
	 *            context请求中的application属性
	 *            该属性在定义的时候，必须遵循约定，以登录为例，即UserLogin.Req的形式
	 *            即UserLogin为service在Spring context中的对应的key首字母大写+.req部分
	 */
	private String getServiceNameFromApplication(String application) {
		if ("".equals(StringUtils.trimToEmpty(application))) {
			return null;
		}
		return StringUtils.substringBefore(
				StringUtils.uncapitalize(application), ".Req")
				+ "Service";
	}

	public static void main(String[] args) {
		String ip = "192.168.1.110, 210.10.10.111";
		String[] ips = ip.split(",");
		ip = ips[ips.length - 1].trim();
		System.out.println(ip);
	}
}
